#!/usr/bin/python
# -*- coding: utf8 -*-
import os, sys, cgi, sqlite3
import cgitb; cgitb.enable()
DB_FILE = 'quiz.sqlite'

def ucgiprint(inline='', unbuff=False, encoding='UTF-8'):
    """Print to the stdout.
     Includes keywords to define the output encoding
     (UTF-8 default, set to None to switch off encoding)
     and also whether we should flush the output buffer
     after every write (default not).
    """
    line_end = '\r\n'
    if encoding:
        inline = inline.encode(encoding)
        # prob. not necessary as line endings will be the
        # same in most encodings
        line_end = line_end.encode(encoding)
    sys.stdout.write(inline)
    sys.stdout.write(line_end)
    if unbuff:
        sys.stdout.flush()

def renderHead():
    head = u"""
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
  <link rel="stylesheet" type="text/css" href="file_res/theme.css" media="screen">
  <meta content="text/html; charset=UTF-8" http-equiv="Content-Type">
  <meta content="Dragon" name="author">
  <meta content="知识测验" name="description">

  <title>知识测验</title>
</head>
<body>
<div id="container">
<div id="mBody" class="Normal">
    """
    ucgiprint (head)


def renderTail():
    tail = """
</div>
</div>
</body>
</html>
    """
    ucgiprint (tail)

def renderBody():
    conn = sqlite3.connect(DB_FILE)
    conn.row_factory = sqlite3.Row
    cur = conn.cursor()
    cur.execute('select * from dragon_quiz')

    count = 0
    i = 1
    for row in cur:
        choices = row['choices'].split('|')
        right_answers = row['right_answers'].split('|')
        ucgiprint ('<div>')
        ucgiprint ('<p>%d. %s</p>' % (count+1, row['question']))

        for index in range(0, len(choices)):
            ucgiprint ('<p><input type="checkbox" name="p%d" value="%d" /><span id="%d_%d">%s</span></p>' % (i, 1 if str(index+1) in right_answers else 0, i, index+1, choices[index]))

        ucgiprint ('</div>')
        i = i+1
        count = count+1

    # Add button
    ucgiprint (u'<input type="button" value="交卷！" onclick="check_answer()"/>')
    ucgiprint (u'<label id="result">&nbsp;</label>')

    # Add scripts
    ucgiprint ("""
<script type="text/javascript">
<!--
function check_answer()
{
    var element;
    var i;
    var wrong = 0;
    var missed = 0;
    var right = 0;
    """)
    for i in range(1, count+1):
        ucgiprint ("""
    element = document.getElementsByName('p%d');
    for (i=0; i<element.length; i++) {
        var spanid = '%d_' + (i+1);
        if (element[i].value == 1 && !element[i].checked) {
            document.getElementById(spanid).style.color = '#00FF00';
            missed++;
        } else if (element[i].value == 0 && element[i].checked) {
            document.getElementById(spanid).style.color = '#FF0000';
            wrong++;
        } else if (element[i].value == 1 && element[i].checked) {
            document.getElementById(spanid).style.color = '#000000';
            right++;
        } else {
            document.getElementById(spanid).style.color = '#A9A5A2';
        }
    }
        """ % (i, i))
    ucgiprint(u"""
    document.getElementById('result').innerHTML = '您的成绩：正确选择：' + right + '  错误选择：'+ wrong + '  漏选：' + missed;
    """)
    ucgiprint ("""
}
//-->
</script>
    """)
    cur.close()

def main():
    #ucgiprint ('Content-type: text/html; charset=utf-8\r\n')
    renderHead()
    renderBody()
    renderTail()


if __name__ == '__main__':
    main()
